//
//  FeedManager.m
//
//  Created by Mechalogical on 27/01/2010.
//  Copyright 2010 Mechalogical Labs.
//
//  This file is part of BattleGrowl.
//  
//  BattleGrowl is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
// 
//  BattleGrowl is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with BattleGrowl.  If not, see <http://www.gnu.org/licenses/>.
// 

#import "FeedManager.h"
#import "WowCharacter.h"


@implementation FeedManager

-(id)init
{
	if ([super init] == nil) return nil;
	
	//start growl manager
	growlManager = [[GrowlManager alloc] init];
	
	// start feedclient
	feedClient = [PSClient applicationClient];
	if( ! feedClient )
        [self fatalError: @"Couldn't get PSClient!"];
		
	
	// Set ourselves as the PSClient delegate
    [feedClient setDelegate: self];
	
	//sync feeds
	[self syncFeedSubscriptions];
	
	//NSDate *test = [NSDate dateWithNaturalLanguageString:@"23 January 2010"];
	
		
	NSDate *lastUpdated = [[NSUserDefaults standardUserDefaults]  objectForKey:@"FeedLastUpdated"];
	if (!lastUpdated) 
	{
		NSLog(@"No last update stored setting feedclient date");
		lastUpdated = [feedClient dateLastUpdated];
	}
	
	NSLog(@"Requesting Entries since %@",lastUpdated);
	
	[feedClient sendChangesSinceDate:lastUpdated];	
	
	[[NSUserDefaults standardUserDefaults] setObject:[feedClient dateLastUpdated] forKey:@"FeedLastUpdated"];
	
	return self;
}

- (void) entriesChanged: (NSNotification*)n
{
	NSLog(@"Feed Update ec");
	//if( [n object] != _currentFeed ) {
    //    // Got PSFeedEntriesChangedNotification for wrong feed!
	//     return;
    //}
	NSLog(@"EntryListController: Entries changed in %@",n);
	// Information as to what exactly changed is included in the userInfo dictionary
    NSDictionary *info = [n userInfo];
	
	// If we've removed entries, just call reloadEntries to resync our table view with the PSFeed's entries
    if( [[info objectForKey: PSFeedRemovedEntriesKey] count] )
        NSLog(@"entries removed");
	
    else {
        // If we've added entries, union them with our existing set of entries
        NSArray *added = [info objectForKey: PSFeedAddedEntriesKey];
        if( added )
		{
			NSLog(@"entries added %d",[added count]);
			NSEnumerator *entries = [added objectEnumerator];
			PSEntry *entry;	
			//get chars
			NSLog(@"Fetching Characters");
			NSFetchRequest *request = [[NSFetchRequest alloc] init];
			[request setEntity:[NSEntityDescription entityForName:@"WowCharacter" inManagedObjectContext:[[NSApp delegate] managedObjectContext]]];
			NSError *error = nil;
			NSArray *characters = [[[NSApp delegate] managedObjectContext] executeFetchRequest:request error:&error];
			[request release];
							
			
			// Go through each entry and print out the title, authors, and content
			while (entry = [entries nextObject]) 
			{
				
				// adding new feeds and updating settings of existing
				for(WowCharacter *character in characters)
				{
					if([[character activityFeedUrl] isEqualToString:[[[entry feed] URL] absoluteString]])
					{
						NSLog(@"adding post for %@",[character name]);
						[growlManager postGrowl:entry forCharacter:character];
					}
				}
				
			}
			[[NSUserDefaults standardUserDefaults] setObject:[feedClient dateLastUpdated] forKey:@"FeedLastUpdated"];
		}
		else
			NSLog(@"none added must be update");
		
        // If it's state changes for existing objects in our set of entries, just update them
        //[self updateEntries: [info objectForKey: PSFeedUpdatedEntriesKey]];
        //[self updateEntries: [info objectForKey: PSFeedDidChangeEntryFlagsKey]];
    }	
}

// Called by PSClient when one or more entries in a feed have been updated
- (void) feed:(PSFeed *)feed didUpdateEntries:(NSArray *)entries
{
    NSLog(@"Feed Update due");
	
}


// Bad things can happen; this is the unpredictable Internet, after all!
// Displays an alert panel, and quits the application.
- (void) fatalError: (NSString*)message
{
    NSRunCriticalAlertPanel(@"Fatal Error!",
                            @"Sorry, battlegrowl is not going to work: %@",
                            @"Quit",nil,nil,
                            message);
    exit(1);
}

- (void) syncFeedSubscriptions 
{
	NSLog(@"Syncing Feed Subscriptions");
	NSLog(@"Fetching Characters");
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	[request setEntity:[NSEntityDescription entityForName:@"WowCharacter" inManagedObjectContext:[[NSApp delegate] managedObjectContext]]];
	NSError *error = nil;
	NSArray *characters = [[[NSApp delegate] managedObjectContext] executeFetchRequest:request error:&error];
	[request release];
		
	// adding new feeds and updating settings of existing
	for(WowCharacter *character in characters)
	{
		NSLog(@"Syncing Character Feed for %@ %@",[character name], [character activityFeedUrl]);
		PSFeed *characterFeed = [feedClient feedWithURL:[NSURL URLWithString:[character activityFeedUrl]]];
		if( !characterFeed )
		{
			NSLog(@"Creating New Feed");
			characterFeed = [feedClient addFeedWithURL:[NSURL URLWithString:[character activityFeedUrl]]]; 
		}
		if( characterFeed )
		{
			NSLog(@"Updating Feed Settings");
			// Retrieve PSFeedSettings object from feed
			PSFeedSettings *feedSettings = characterFeed.settings;
			// Set entries to expire after 30 days (60 s/m * 60m/h * 24 h/d * 30 d) 
			feedSettings.expirationInterval = 2592000;
			// Set feed to check for updates every 30 minutes (60 s/m * 30m) 
			feedSettings.refreshInterval = 60 * [[NSUserDefaults standardUserDefaults] integerForKey:@"FeedRefreshInterval"];
			// Store settings back in the feed 
			characterFeed.settings = feedSettings;
			// And add ourself as observer of this new feed's PSFeedEntriesChangedNotification		
			[[NSNotificationCenter defaultCenter] addObserver: self
												selector: @selector(entriesChanged:)
												name: PSFeedEntriesChangedNotification 
												object: characterFeed];
		}
		else
		{
			NSLog(@"Could not create feed");
		}
	}
	
	///removing old feeds
	for(PSFeed *feed in [feedClient feeds])
	{
		NSLog(@"Removal Scanning Character Feed %@",[[feed URL] absoluteString]);
		bool found = false;
		for(WowCharacter *character in characters)
		{			
			if([[character activityFeedUrl] isEqualToString:[[feed URL] absoluteString]])
			{
				found = true;
			} 
		}
		if(!found)
		{
			NSLog(@"Removing Character Feed %@",[[feed URL] absoluteString]);
			[feedClient removeFeed:feed];
		}
	}
}

@end
